package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements IWeChatService {


    @Value("${weChat.appId}")
    private String appid;

    @Value("${weChat.appSecret}")
    private String secret;

    private static String openIdURL = "https://api.weixin.qq.com/sns/jscode2session";
    private static String phoneURL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static String tokenURL = "https://api.weixin.qq.com/cgi-bin/token";

    @Override
    public String getOpenid(String code) {

        Map paramMap = new HashMap();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");


        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, openIdURL)
                // .body()
                .form(paramMap).execute();

        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            // 把字符串转成对象
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String openid = jsonObject.getStr("openid");

            return openid;
        }

        return null;
    }

    @Override
    public String getPhone(String phoneCode) {
        Map paramMap = new HashMap();
        paramMap.put("code",phoneCode);

        HttpResponse httpResponse = HttpUtil.createRequest(Method.POST, phoneURL+token())
                .body(JSONUtil.toJsonStr(paramMap))
                .execute();

        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            // 把字符串转成对象
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String phone = jsonObject.getByPath("phone_info.phoneNumber",String.class);
            return phone;
        }

        return null;
    }


    public String token(){
        Map paramMap = new HashMap();
        paramMap.put("appid",appid);
        paramMap.put("secret",secret);
        paramMap.put("grant_type","client_credential");


        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, tokenURL)
                // .body()
                .form(paramMap).execute();

        if (httpResponse.isOk()) {
            String body = httpResponse.body();
            // 把字符串转成对象
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String token = jsonObject.getStr("access_token");

            return token;
        }

        return null;
    }
}
